package com.sihai.ehr.repository;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.sihai.core.DataAccessor;
import com.sihai.core.QueryCreator;
import com.sihai.ehr.model.sys.Organization;

/**
 * 员工仓库服务
 * 
 * @author Henry
 * 
 */
@Repository
public class EmployeeRepository {
	@Resource
	private DataAccessor dataAccessor;

	/**
	 * 根据组织结构编号统计员工数
	 * 
	 * @param orgId
	 * @return
	 */
	public Long getTotalCountByOrganizationId(final Long orgId,
			boolean isReadChild) {
		if (orgId > 0) {
			try {
				if (isReadChild) {
					String treepath = dataAccessor.get(Organization.class,
							orgId).getTreePath();

					final String orgRealtion = treepath;
					return this.dataAccessor.findUnique(Long.class,
							new QueryCreator() {
								@Override
								public Query createQuery(Session session) {
									return session
											.createQuery("select count(o.id) from EmployeeinfoWork o where o.organization.treePath like '"
													+ orgRealtion + "%'");
								}
							});
				} else {
					return this.dataAccessor.findUnique(Long.class,
							new QueryCreator() {
								@Override
								public Query createQuery(Session session) {
									return session
											.createQuery("select count(o.id) from EmployeeinfoWork o where o.organization.id="
													+ orgId);
								}
							});
				}
			} catch (Exception e) {
				throw new RuntimeException(
						"【统计部门人数异常】【异常原因：:"
								+ e.getMessage()
								+ "】【发生地点：EmployeeServiceImpl.getTotalCountByOrganizationId】");
			}

		} else {
			return 0L;
		}
	}
}
